package com.cola.dao;

import com.cola.action.UserAction;
import com.cola.entity.Customer;
import com.cola.entity.User;
import com.cola.entity.WeChatInfo;
import com.cola.enums.UserType;
import com.cola.utils.DBControl;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户Dao
 * @author Max
 * @since 2017/9/13
 */
public class UserDao extends BaseDao{
    private static final Logger logger = LoggerFactory.getLogger(UserAction.class);
    private static volatile UserDao instance = null;

    public static UserDao getInstance() {
        if (instance == null) {
            synchronized (UserDao.class) {
                if (instance == null) {
                    instance = new UserDao();
                }
            }
        }
        return instance;
    }

    /**
     * 更新用户信息
     * @param weChatInfo ;微信信息
     * @return 
     * @author Max
     * @since 2017/9/14
     */
    public boolean updateUserWeChatInfo(WeChatInfo weChatInfo,String userType){
        Connection conn = null;
        String sql = "";

        try{
            switch (userType){
                case "SHOP": sql="update cola_customer set customer_wechat_nick =? ,customer_head_img_url =? where customer_open_id =?";break;
                case "MEP":sql="update cola_mep set mep_wechat_nick =? ,mep_head_img_url =? where mep_open_id =?";break;
                case "COURIER":sql="update cola_courier set courier_wechat_nick =? ,courier_head_img_url =? where courier_open_id =?";break;
            }
            if(StringUtils.isNotEmpty(sql)){
                conn = DBControl.getConnection();
                return getQueryRunner().update(conn,sql,weChatInfo.getNickname(),weChatInfo.getHeadimgurl(),weChatInfo.getOpenid())>0;
            }
        }catch (Exception e){
            logger.error("更新用户微信信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return false;
    }

    /**
     * 更新用户微信信息
     * @param weChatInfo userType mobile;微信信息
     * @return
     * @author Max
     * @since 2017/9/14
     */
    public boolean updateWeChatInfo(WeChatInfo weChatInfo,String userType,String mobile){
        Connection conn = null;
        String sql = "";

        try{
            switch (userType){
                case "SHOP": sql="update cola_customer set customer_open_id=?,customer_wechat_nick =? ,customer_head_img_url =? where customer_mobile =?";break;
                case "MEP":sql="update cola_mep set mep_open_id=?,mep_wechat_nick =? ,mep_head_img_url =?,is_bind=1 where mep_mobile =?";break;
                case "COURIER":sql="update cola_courier set courier_open_id=?, courier_wechat_nick =? ,courier_head_img_url =? where courier_mobile =?";break;
            }
            if(StringUtils.isNotEmpty(sql)){
                conn = DBControl.getConnection();
                return getQueryRunner().update(conn,sql,weChatInfo.getOpenid(),weChatInfo.getNickname(),weChatInfo.getHeadimgurl(),mobile)>0;
            }
        }catch (Exception e){
            logger.error("更新用户微信信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return false;
    }



    /**
     * 根据mobile获取用户信息
     * @param mobile
     * @return User
     * @author Max
     * @since 2017/9/13
     */
    public User getShopInfo(String mobile){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();
        try{
            conn = DBControl.getConnection();
            String sql = "select * from cola_customer where  customer_mobile=?  ";
            ps = conn.prepareStatement(sql);
            ps.setString(1,mobile);
            rs = ps.executeQuery();
            if(rs.next()){
                user.setMobile(rs.getString("customer_mobile"));
                user.setUserId(rs.getInt("customer_id"));
                user.setIsBind(rs.getInt("is_bind"));
                user.setCheckStatus(rs.getInt("check_status"));
                user.setSysNo(rs.getString("customer_system_no"));
                user.setStatus(rs.getInt("status"));
                user.setColaNo(rs.getString("customer_no"));
                user.setAreaNo(rs.getString("area"));
                user.setCityNo(rs.getString("city"));
                user.setChannelNo(rs.getString("channel_type_no"));
            }
            user.setUserType(UserType.SHOP.getValue());
            return user;
        }catch (Exception e){
            logger.error("获取用户信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return null;
    }

    /**
     * 检查手机号是否被注册过
     * @param mobile
     * @return true:已经注册过;false:未注册
     * @author Max
     * @since 2017/9/13
     */
    public boolean checkMobile(String mobile,Integer customerId){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();
        try{
            conn = DBControl.getConnection();
            String sql = "select count(customer_id) from cola_customer where  customer_mobile=? and customer_id<>?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,mobile);
            ps.setInt(2,customerId);
            rs = ps.executeQuery();
            if(rs.next()){
                return rs.getInt(1)>0;
            }
        }catch (Exception e){
            logger.error("检查手机号是否被注册过异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return true;
    }

    /**
     * 检查手机号是否被注册过
     * @param mobile
     * @return true:已经注册过;false:未注册
     * @author Max
     * @since 2017/9/13
     */
    public boolean checkMobile(String mobile){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();
        try{
            conn = DBControl.getConnection();
            String sql = "select count(customer_id) from cola_customer where  customer_mobile=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,mobile);
            rs = ps.executeQuery();
            if(rs.next()){
                return rs.getInt(1)>0;
            }
        }catch (Exception e){
            logger.error("检查手机号是否被注册过异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return true;
    }


    /**
     * 获取经销商信息
     * @param mobile
     * @return User
     * @author Max
     * @since 2017/9/13
     */
    public User getMepInfo(String mobile){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();
        try{
            conn = DBControl.getConnection();
            String sql = "select * from cola_mep where mep_mobile=? ";
            ps = conn.prepareStatement(sql);
            ps.setString(1,mobile);
            rs = ps.executeQuery();
            if(rs.next()){
                user.setMobile(rs.getString("mep_mobile"));
                user.setUserId(rs.getInt("mep_id"));
                user.setIsBind(rs.getInt("is_bind"));
                user.setStatus(rs.getInt("status"));
                user.setColaNo(rs.getString("mep_no"));
                user.setAreaNo(rs.getString("area"));
                user.setCityNo(rs.getString("city"));
            }
            user.setUserType(UserType.MEP.getValue());
            return user;
        }catch (Exception e){
            logger.error("获取经销商信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return null;
    }

    /**
     * 根据mobile获取配送员信息
     * @param mobile
     * @return User
     * @author Max
     * @since 2017/9/13
     */
    public User getCourierInfo(String mobile){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();
        try{
            conn = DBControl.getConnection();
            String sql = "select * from cola_courier where   courier_mobile=? ";
            ps = conn.prepareStatement(sql);
            ps.setString(1,mobile);
            rs = ps.executeQuery();
            if(rs.next()){
                user.setMobile(rs.getString("courier_mobile"));
                user.setUserId(rs.getInt("courier_id"));
                user.setStatus(rs.getInt("status"));
            }
            user.setUserType(UserType.COURIER.getValue());
            return user;
        }catch (Exception e){
            logger.error("获取配送员信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return null;
    }

    
    /**
     * 检查用户信息是否正确
     * @param mobile ,openId,userType
     * @return 
     * @author Max
     * @since 2017/9/14
     */
    public boolean checkUserInfo(String mobile,String openId,String userType){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "";
        try{
            switch (userType){
                case "SHOP": sql="select customer_id from cola_customer where customer_open_id =? and customer_mobile=?";break;
                case "MEP":sql="select mep_id from cola_mep where mep_open_id =? and mep_mobile=?";break;
                case "COURIER":sql="select courier_id from cola_courier where courier_open_id =? and courier_mobile=?";break;
            }
            if(StringUtils.isNotEmpty(sql)){
                conn = DBControl.getConnection();
                ps = conn.prepareStatement(sql);
                ps.setString(1,openId);
                ps.setString(2,mobile);
                rs = ps.executeQuery();
                if(rs.next()){
                    return rs.getInt(1)>0;
                }
            }
        }catch (Exception e){
            logger.error("检查用户信息是否正确异常！",e);
        }finally {
            DbUtils.closeQuietly(conn,ps,rs);
        }
        return false;
    }

    /**
     * 根据店铺系统编号获取店铺信息
     * @param systemNo
     * @return Customer
     * @author Max
     * @since 2017/9/16
     */
    public Customer getCustomerInfoBySystemNo(String systemNo){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "SELECT a.*,b.`area_name` as city_name,c.`area_name` as area_name FROM `cola_customer` a " +
                    "INNER JOIN system_area b on a.city = b.area_no " +
                    "INNER JOIN system_area c on a.area = c.area_no where customer_system_no=?";
            return getQueryRunner().query(conn,sql,new BeanHandler<Customer>(Customer.class),systemNo);
        }catch (Exception e){
            logger.error("根据店铺系统编号获取店铺信息异常！",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }


    public static void main(String[] args) {
    }
}
